package com.xul.srb.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xul.common.exception.Assert;
import com.xul.common.result.ResponseEnum;
import com.xul.srb.base.uitl.JwtUtils;
import com.xul.srb.core.enums.UserBindEnum;
import com.xul.srb.core.hfb.FormHelper;
import com.xul.srb.core.hfb.HfbConst;
import com.xul.srb.core.hfb.RequestHelper;
import com.xul.srb.core.mapper.UserBindMapper;
import com.xul.srb.core.mapper.UserInfoMapper;
import com.xul.srb.core.pojo.entity.UserBind;
import com.xul.srb.core.pojo.entity.UserInfo;
import com.xul.srb.core.pojo.vo.UserBindVO;
import com.xul.srb.core.service.UserBindService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 服务实现类
 * </p>
 *
 * @author xul
 * @since 2021-11-06
 */
@Slf4j
@Service
public class UserBindServiceImpl extends ServiceImpl<UserBindMapper, UserBind> implements UserBindService {

    @Resource
    private UserInfoMapper userInfoMapper;

    /**
     * 账户绑定提交数据
     *
     * @param userBindVO
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String bindUser(UserBindVO userBindVO, HttpServletRequest request) {
        // 从token活动到userId
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);

        // userBindVO表单信息的后端校验

        // 判断一个身份证号只能绑定一个用户
        QueryWrapper<UserBind> wrapper = new QueryWrapper<>();
        wrapper.eq("id_card", userBindVO.getIdCard()).ne("user_id", userId);
        UserBind userBind = baseMapper.selectOne(wrapper);
        // USER_BIND_IDCARD_EXIST_ERROR(-301, "身份证号码已绑定")
        Assert.isNull(userBind, ResponseEnum.USER_BIND_IDCARD_EXIST_ERROR);

        // 一个用户只能对应一个数据绑定信息 通过userId从数据库查询用户绑定信息 如果存在就经行修改 不存在就经行添加
        wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        userBind = baseMapper.selectOne(wrapper);
        if (userBind == null) {
            // 创建一个新的用户
            userBind = new UserBind();
            BeanUtils.copyProperties(userBindVO, userBind);
            userBind.setStatus(UserBindEnum.NO_BIND.getStatus());
            userBind.setUserId(userId);
            baseMapper.insert(userBind);
        } else {
            BeanUtils.copyProperties(userBindVO, userBind);
            baseMapper.updateById(userBind);
        }

        // 组装表单信息
        Map<String, Object> map = new HashMap<>();
        // 第三方平台给商户分配的唯一标识
        map.put("agentId", HfbConst.AGENT_ID);
        // 组装前台传过来的表单信息
        map.put("agentUserId", userId);
        map.put("idCard", userBindVO.getIdCard());
        map.put("personalName", userBindVO.getName());
        map.put("bankType", userBindVO.getBankType());
        map.put("bankNo", userBindVO.getBankNo());
        map.put("mobile", userBindVO.getMobile());
        // 用户绑定同步回调 http://localhost:3000/user
        map.put("returnUrl", HfbConst.USERBIND_RETURN_URL);
        // 用户绑定异步回调 http://localhost/api/core/userBind/notify
        map.put("notifyUrl", HfbConst.USERBIND_NOTIFY_URL);
        // 获取当前时间戳
        map.put("timestamp", RequestHelper.getTimestamp());
        // 对签名经行加密
        map.put("sign", RequestHelper.getSign(map));

        // 构建用户信息并提交表单到第三方平台 http://localhost:9999/userBind/BindAgreeUserV2
        return FormHelper.buildForm(HfbConst.USERBIND_URL, map);
    }

    /**
     * 账户绑定异步回调 并将第三方绑定的数据更新到数据库
     *
     * @param request
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void notifyBand(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 将parameterMap转换成Map<String, Object>这个格式
        Map<String, Object> map = RequestHelper.switchMap(parameterMap);
        // 经行签名的校验
        if (!RequestHelper.isSignEquals(map)) {
            log.error("用户账号绑定异步回调签名错误：" + JSON.toJSONString(map));
        }

        // 获取用户的user_id
        String userId = (String) map.get("agentUserId");
        // 获取签名bind_code
        String bindCode = (String) map.get("bindCode");

        // 更新用户绑定表的信息
        QueryWrapper<UserBind> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserBind userBind = baseMapper.selectOne(wrapper);
        userBind.setBindCode(bindCode);
        userBind.setStatus(UserBindEnum.BIND_OK.getStatus());
        baseMapper.updateById(userBind);

        // 更新会员信息表的信息
        UserInfo userInfo = userInfoMapper.selectById(userId);
        userInfo.setBindCode(bindCode);
        userInfo.setBindStatus(UserBindEnum.BIND_OK.getStatus());
        userInfo.setName(userBind.getName());
        userInfo.setIdCard(userBind.getIdCard());
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 根据userId 获取 bindCode
     *
     * @param userId
     * @return
     */
    @Override
    public String getBindCodeByUserId(Long userId) {
        QueryWrapper<UserBind> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserBind userBind = baseMapper.selectOne(wrapper);
        return userBind.getBindCode();
    }
}
